<?php
/**
 *  💡 免责声明：本软件不得用于商业用途，仅做学习交流
 *  ⚠️ 权利声明：本软件由版权人提供产品技术支持
 *  📅 项目编号：NX2025-0135
 */
namespace App\Admin\Controllers;

use App\Admin\Actions\Grid\ShowUserTree;
use App\Admin\Actions\Grid\ShowUserTreeData;
use App\Admin\Actions\Row\UserAddPointAction;
use App\Admin\Repositories\User;
use App\Models\PerformanceLevel;
use App\Models\UserLevelSetting;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Show;
use Dcat\Admin\Widgets\Modal;

class UserController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new User(['performanceLevel', 'teamMember', 'GroupOrderCount']), function (Grid $grid) {
//            $grid->disableCreateButton();
            $grid->disableRowSelector();
            $grid->model()->orderBy('team', 'desc');
            $grid->column('id')->sortable();
            $grid->column('parent', '推荐人ID')->copyable();
            $grid->column('flag', '标签')->editable();
            $grid->column('name');
            $grid->column('telephone')->copyable();
//            $grid->column('password');
            $grid->column('profile')->image('', 50, 50);
            $grid->column('contribution_value', '贡献值');
            $grid->column('GroupOrderCount', '拼单数')->display(function ($v) {
                return $v->count();
            })->sortable();

            $grid->column('team', '团队数')->sortable();
            $grid->column('团队人员')->display(function () {
                if ($this->team > 0) {
                    // 使用 Modal 加载远程内容
                    return Modal::make()
                        ->lg()
                        ->title('数据详情')
                        ->body(ShowUserTree::make(['key' => $this->getKey()])) // 动态URL
                        ->button('<i class="fa fa-eye"></i> 查看')
                        ->scrollable();
                }
                return '';
            });
            $grid->column('member_level')->sortable();
            $grid->column('uuid');
            $grid->column('info', '数据统计')->display(function () {
                return <<<HTML
<a href="/getUserData/{$this->id}" target="_blank">数据详情</a>
HTML;
            });
            $grid->column('performanceLevel.name', '代理商等级')->display(function ($name) {
                if (! $name) {
                    return 0;
                }
                return $name;
            })->sortable();
            $grid->column('teamMember.total_amount', '总业绩')->sortable();
            $grid->column('teamMember.max_team_amount', '最大部门业绩')->sortable();
            $grid->column('teamMember.small_teams_sum', '小部门之和')->sortable();
            $grid->column('teamMember.calculation_date', '计算时间')->sortable();

            $grid->column('teamModal', '部门数据')->display(function () {
                $teams = $this->teamMember->team_data['teams'] ?? null;
                if ($teams) {
                    return Modal::make()
                        ->lg()
                        ->title('部门数据')
                        ->body(ShowUserTreeData::make(['key' => $teams])) // 动态URL
                        ->button('<i class="fa fa-eye"></i> 查看')
                        ->scrollable();
                }
                return '';
            });
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableDelete();
                $actions->append(new UserAddPointAction());
            });
            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
                $filter->equal('name');
                $filter->like('telephone');
                $filter->between('created_at', '创建时间')->datetime();
                $filter->between('updated_at', '修改时间')->datetime();
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new User(), function (Show $show) {
            $show->field('id');
            $show->field('name');
            $show->field('telephone');
            $show->field('password');
            $show->field('transaction_password');
            $show->field('profile');
            $show->field('parent');
            $show->field('member_level');
            $show->field('agent_level');
            $show->field('uuid');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new User(), function (Form $form) {
            if ($form->isCreating()) {
                $form->select('parent')->options($this->getUser())->required();
                $form->text('uuid')->default(1234);
            }
            $form->text('name')->default('虚拟账户');
            $form->image('profile')->autoUpload();
            $form->display('id');
            $form->text('flag');
            $form->text('telephone');
            $form->text('password');
            $form->text('transaction_password');
            $form->number('contribution_value', '贡献值');
            $form->select('member_level')->options($this->getMemberLevel())->default(0);
            $form->select('agent_level')->options($this->agentLevel())->default(0);

            $form->saving(function (Form $form) {
                if ($form->password && $form->model()->find($form->getKey())->password != $form->password) {
                    $form->password = bcrypt($form->password);
                }
                if ($form->transaction_password && $form->model()->find($form->getKey())->transaction_password != $form->transaction_password) {
                    $form->transaction_password = bcrypt($form->transaction_password);
                }

                if (! $form->password) {
                    $form->deleteInput('password');
                }
                if ($form->parent != 0) {
                    \App\Models\User::query()->find($form->parent)->increment('team');
                }

                if (! $form->password) {
                    $form->deleteInput('password');
                }
            });
            $form->display('created_at');
            $form->display('updated_at');
        });
    }

    // 子部门表格定义
    private function getMemberLevel()
    {
        $res = UserLevelSetting::query()->pluck('level', 'id')->toArray();

        $res[0] = 0;
        return $res;
    }

    private function agentLevel()
    {
        $res = PerformanceLevel::query()->pluck('name', 'id')->toArray();
        $res[0] = 0;
        return $res;
    }

    private function getUser()
    {
        $res = \App\Models\User::query()->pluck('telephone', 'id')->toArray();
        $res[0] = 0;
        return $res;
    }
}
